import { Component } from "@vue/runtime-core";
import { RouteLocationNormalized } from "vue-router";
import Home from "./layout/Home.vue";
import LayoutManager from "./layout/LayoutManager";
import router from "./router";
import $store from "./store";
import { useGlobalMessage, useGlobalRouter } from "./utils/global";

const titleAfterfix = ' | Cloud米米商城';

router.beforeEach(async (to: RouteLocationNormalized & { [props: string]: any }, from) => {
  if (to?.meta?.beforeEnter) {
    if (!(to.meta.beforeEnter as any)())
      return false;
  }
  resolveTitle(to);
  let pass = await resolveMeta(to, from);
  if (!pass) return false;
  return true;
});

function resolveTitle(to: any) {
  document.title = (to?.meta?.title as string || '商城') + titleAfterfix;
}

async function resolveMeta(to: RouteLocationNormalized, from: RouteLocationNormalized) {
  const {
    meta: {
      layout = Home,
      needLogin = false,
    } = {},
  } = to;
  if (needLogin && !$store.getters.getUserInfo) {
    useGlobalMessage().warning('请先登录');
    return false;
  }
  $store.dispatch('updateLayout', layout);
  return true;
}
